package com.bawei.detail

import android.os.Bundle
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.bawei.common.entity.MovieEntity
import com.bawei.common.mvi.BaseMviFragment
import com.bawei.detail.adapter.DetailMovieListAdapter
import com.bawei.detail.databinding.FragmentIntroduceBinding
import com.bawei.detail.entity.AuthorEntity
import com.bawei.detail.viewmodel.DetailViewModel
import com.bawei.image.ImageOptions
import com.bawei.image.ImageStrategy
import com.bawei.image.ImgLoader
import com.bumptech.glide.Glide
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class IntroduceFragment : BaseMviFragment<FragmentIntroduceBinding>() {

    private val mViewModel: DetailViewModel by activityViewModels()

    private var imgLoader: ImgLoader = ImgLoader.Builder.setImageStrategy(ImageStrategy.GLIDE).build()
    //普通图片参数
    private var imgOption: ImageOptions = ImageOptions.Builder
        .setImageSize(intArrayOf(80, 80))
        .setCircleImage(true)
        .skipMemoryCache(true)
        .build()

    private var movieList = mutableListOf<MovieEntity>()
    private lateinit var mMovieAdapter: DetailMovieListAdapter
    private lateinit var mRecyclerView: RecyclerView
    private var userId = ""
    private var typeId = -1

    companion object {
        @JvmStatic
        fun newInstance(userId: String, typeId: Int) =
            IntroduceFragment().apply {
                arguments = Bundle().apply {
                    putString("userId", userId)
                    putInt("typeId", typeId)
                }
            }
    }

    override fun getLayoutId(): Int = R.layout.fragment_introduce

    override fun initViews() {
        //获取参数
        userId = arguments?.getString("userId").toString()
        typeId = arguments?.getInt("typeId")!!

        //初始化RecyclerView
        //初始化RecyclerView
        mRecyclerView = mDataBinding.rvUserVideo
        //默认ItemView缓存大小为2, 数值越大缓存的Item就越多，占用内存就越大
        mRecyclerView.setItemViewCacheSize(10)
        mRecyclerView.setHasFixedSize(true) //Item布局大小为固定大小

        //适当调整缓存池大小, 默认缓存池的大小为5
        var pool = RecyclerView.RecycledViewPool()
        pool.setMaxRecycledViews(0, 5)
        mRecyclerView.setRecycledViewPool(pool)

        //根据RecyclerView的滚动事件来暂停或恢复加载
        mRecyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(this@IntroduceFragment).resumeRequests() //恢复图片加载
                } else {
                    Glide.with(this@IntroduceFragment).pauseRequests() //暂停图片加载
                }
            }
        })

        //取消不需要的Item动画
        (mRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false

        mRecyclerView.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.VERTICAL, false)
        mMovieAdapter = DetailMovieListAdapter(movieList)
        mRecyclerView.swapAdapter(mMovieAdapter, true)
    }


    override suspend fun sendViewIntent() {
        //获取作者信息
        mViewModel.channel.send(DetailViewIntent.LoadAuthorInfo(userId))
        //获取类似视频
        if(typeId == -1){
           mViewModel.channel.send(DetailViewIntent.LoadRecommendMovieList(1, 10))
        } else{
            mViewModel.channel.send(DetailViewIntent.LoadMovieList(typeId, 1,10))
        }
    }

    override suspend fun collectUIState() {
        mViewModel.uiState.collect{
            when(it){
                is DetailUiState.LoadAuthorSuccess -> updateAuthorInfo(it.entity)
                is DetailUiState.LoadMovieListSuccess -> updateMovieList(it.list)
                is DetailUiState.LoadAuthorFail -> showToastMessage(it.msg)
                is DetailUiState.LoadMovieListFail -> showToastMessage(it.msg)
                else -> {}
            }
        }
    }

    private fun updateAuthorInfo(entity: AuthorEntity) {
        imgLoader.loadUrlIntoImageView(requireContext(), entity.avatar_url, mDataBinding.civUserIcon, imgOption)
        mDataBinding.tvUserName.text = entity.description
        mDataBinding.tvLikeCount.text = entity.followerscount
        mDataBinding.tvSendTime.text = entity.ctime
    }

    private fun updateMovieList(list: List<MovieEntity>){
        if(movieList.isNotEmpty()){
            movieList.clear()
        }

        movieList.addAll(list)
        mMovieAdapter.notifyDataSetChanged()

    }

}